package Ep05_StackAndQueue._0347;

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/4/14 9:48
 * 说明：(x)HashMap+Stream解法(x) 了解即可
 */

public class Mine {
    public int[] topKFrequent(int[] nums, int k) {
        if (nums.length == k){
            return nums;
        }
        Map<Integer, Integer> map = new LinkedHashMap<>();
        Arrays.stream(nums).forEach(x -> {
            if (map.containsKey(x)) {
                map.put(x, map.get(x) + 1);
            } else {
                map.put(x, 1);
            }
        });

        int[] res = map.entrySet().stream().sorted((o1, o2) ->
                o2.getValue() - o1.getValue()).limit(k).mapToInt(Map.Entry::getKey).toArray();
        return res;
    }
}
